package com.viphuli.app.tool.fragment;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TimePicker;
import butterknife.Bind;
import butterknife.OnClick;

import com.loopj.android.http.RequestParams;
import com.offroader.utils.DateUtils;
import com.offroader.utils.StringUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.bean.part.ArrangeType;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.MyPageHelper;
import com.viphuli.app.tool.fragment.NumberPickerDialogFragment.NumberClickListener;
import com.viphuli.app.tool.http.ApiRequest;
import com.viphuli.app.tool.utils.OtherUtils;

/**
 * 排班信息修改
 * 
 * @author li.li
 * 
 */
public class ArrangeTypeEditFragment extends BaseProgressFragment implements OnCheckedChangeListener {

	private static final String[] types = new String[] { "工作", "休假" };

	//当前类型索引
	private int curType;

	@Bind(R.id.id_home_item_arrange_type)
	protected TextView type;

	@Bind(R.id.id_home_item_arrange_type_name)
	protected TextView name;

	@Bind(R.id.id_home_item_arrange_type_start)
	protected TextView start;

	@Bind(R.id.id_home_item_arrange_type_start_layout)
	protected View startLayout;

	@Bind(R.id.id_home_item_arrange_type_end)
	protected TextView end;

	@Bind(R.id.id_home_item_arrange_type_end_layout)
	protected View endLayout;

	@Bind(R.id.id_home_item_arrange_type_color_layout)
	protected RadioGroup colorTab;

	@Bind(R.id.id_holiday_leave_duration)
	protected TextView durationText;

	@Bind(R.id.id_holiday_leave_duration_layout)
	protected View durationLayout;

	@Bind(R.id.id_holiday_leave_remark)
	protected TextView remark;

	@Bind(R.id.id_holiday_leave_remark_layout)
	protected View remarkLayout;

	private ArrangeType arrangeTypeInfo;

	private int duration;

	// 当前选择的颜色
	private String checkColor;

	private long startTime;

	private long endTime;

	private int arrangeTypeId;

	@Override
	protected int obtainContentRes() {
		return R.layout.frag_arrange_type_edit;
	}

	@Override
	protected void initParams() {
		// 解析参数
		Bundle args = getArguments();
		arrangeTypeId = args.getInt("arrange_type_id", 0);
		curType = args.getInt("cur_type", 0);

	}

	@Override
	protected void initView() {
		colorTab.setOnCheckedChangeListener(this);

		if (curType == 0) {

			durationLayout.setVisibility(View.GONE);
			remarkLayout.setVisibility(View.GONE);

		} else {

			startLayout.setVisibility(View.GONE);
			endLayout.setVisibility(View.GONE);

		}

		type.setText(types[curType]);

	}

	@Override
	protected void initData() {

		if (arrangeTypeId != 0) {

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

			if (tokenKeeper.isLogin()) {

				RequestParams params = new RequestParams();
				params.put("circle_id", tokenKeeper.getUser().circleId());
				params.put("arrange_type_id", arrangeTypeId);

				ApiRequest.arrangeTypeInfo.request(this, params);

			}

		}

	}

	@OnClick(R.id.id_home_item_arrange_type)
	public void clickType() {

		showSingleChoiceButton();

	}

	@OnClick(R.id.id_home_item_arrange_type_start)
	public void clickStarTime(TextView textView) {

		if (startTime == 0 && arrangeTypeInfo != null)
			startTime = arrangeTypeInfo.getStart() * 1000;

		int hour = DateUtils.getHour(new Date(startTime));
		int minute = DateUtils.getMinute(new Date(startTime));

		showTimePickderDialog(hour, minute, textView, 1);

	}

	@OnClick(R.id.id_home_item_arrange_type_end)
	public void clickEndTime(TextView textView) {

		if (endTime == 0 && arrangeTypeInfo != null)
			endTime = arrangeTypeInfo.getEnd() * 1000;

		int hour = DateUtils.getHour(new Date(endTime));
		int minute = DateUtils.getMinute(new Date(endTime));

		showTimePickderDialog(hour, minute, textView, 2);

	}

	@Override
	public void onCheckedChanged(RadioGroup button, int checkedId) {

		switch (checkedId) {
		case R.id.id_home_item_arrange_type_color_1:

			checkColor = getString(R.color.cl_home_item_arrange_type_color_1);

			break;

		case R.id.id_home_item_arrange_type_color_2:

			checkColor = getString(R.color.cl_home_item_arrange_type_color_2);

			break;

		case R.id.id_home_item_arrange_type_color_3:

			checkColor = getString(R.color.cl_home_item_arrange_type_color_3);

			break;

		case R.id.id_home_item_arrange_type_color_4:

			checkColor = getString(R.color.cl_home_item_arrange_type_color_4);

			break;

		default:
			break;
		}

	}

	@OnClick(R.id.id_account_submit_btn)
	public void submit() {

		if (arrangeTypeId != 0) {

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

			if (tokenKeeper.isLogin()) {
				

				RequestParams params = new RequestParams();
				params.put("circle_id", tokenKeeper.getUser().circleId());
				params.put("arrange_type_id", arrangeTypeId);
				

				//1：班次，3：长假
				if (curType == 0) {
					
					params.put("uid", tokenKeeper.getUser().getUid());
					params.put("name", name.getText().toString());
					params.put("start", OtherUtils.maxLength(startTime));
					params.put("end", OtherUtils.maxLength(endTime));
					params.put("type", 1);
					params.put("hour", (OtherUtils.maxLength(endTime) - OtherUtils.maxLength(startTime)) / 60 / 60);
					params.put("color", checkColor);

					
				}else {
					
					params.put("uid", tokenKeeper.getUser().getUid());
					params.put("name", name.getText().toString());
					params.put("start", 0);
					params.put("end", 0);
					params.put("type", 3);//休假
					params.put("hour", duration * 8);
					params.put("color", checkColor);
					
				}
				
				ApiRequest.arrangeTypeInfoChange.request(this, params);

			}

		} else {
			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

			if (tokenKeeper.isLogin()) {

				RequestParams params = new RequestParams();

				//1：班次，3：长假
				if (curType == 0) {

					params.put("uid", tokenKeeper.getUser().getUid());
					params.put("name", name.getText().toString());
					params.put("start", OtherUtils.maxLength(startTime));
					params.put("end", OtherUtils.maxLength(endTime));
					params.put("color", checkColor);
					params.put("type", 1);
					params.put("hour", (OtherUtils.maxLength(endTime) - OtherUtils.maxLength(startTime)) / 60 / 60);
					params.put("remark", "");

				} else {

					params.put("uid", tokenKeeper.getUser().getUid());
					params.put("name", name.getText().toString());
					params.put("start", 0);
					params.put("end", 0);
					params.put("type", 3);//休假
					params.put("hour", duration * 8);
					params.put("color", checkColor);

					if (StringUtils.isNotBlank(remark.getText().toString())) {
						params.put("remark", remark.getText().toString());
					}

				}

				ApiRequest.arrangeTypeInfoAdd.request(this, params);

			}
		}

	}

	/**
	 * 时间选择对话框
	 * 
	 * @param hour
	 * @param minute
	 * @param textView
	 * @param timeType
	 *            1开始 2结束
	 */
	private void showTimePickderDialog(int hour, int minute, final TextView textView, final int timeType) {

		new TimePickerDialog(getActivity(), new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int inthourOfDay, int minute) {

				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(System.currentTimeMillis());
				c.set(Calendar.HOUR_OF_DAY, inthourOfDay);
				c.set(Calendar.MINUTE, minute);
				c.set(Calendar.SECOND, 0);
				c.set(Calendar.MILLISECOND, 0);

				String time = DateUtils.format_hm.format(c.getTime());
				textView.setText(time);

				if (timeType == 1)
					startTime = c.getTimeInMillis();
				else
					endTime = c.getTimeInMillis();

			}
		}, hour, minute, true).show();

	}

	@OnClick(R.id.id_holiday_leave_duration)
	public void clickDuration() {

		NumberPickerDialogFragment dialogFrag = new NumberPickerDialogFragment(new NumberClickListener() {

			@Override
			public void onEnsure(int number) {

				if (number > 0) {
					durationText.setText(number + "天");
					ArrangeTypeEditFragment.this.duration = number;
				}
			}
		}, 1, 150, "天");

		dialogFrag.show(getChildFragmentManager(), dialogFrag.getClass().getSimpleName());

	}

	private void showSingleChoiceButton() {

		int index = 0;//默认先第一个
		curType = index;

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("请选择类型");
		builder.setSingleChoiceItems(types, index, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				curType = which;
			}
		});

		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				type.setText(types[curType]);

				if (curType == 0) {

					durationLayout.setVisibility(View.GONE);
					remarkLayout.setVisibility(View.GONE);

					startLayout.setVisibility(View.VISIBLE);
					endLayout.setVisibility(View.VISIBLE);

				} else {

					durationLayout.setVisibility(View.VISIBLE);
					remarkLayout.setVisibility(View.VISIBLE);

					startLayout.setVisibility(View.GONE);
					endLayout.setVisibility(View.GONE);

				}

			}
		});

		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		builder.show();

	}

	public TextView getName() {
		return name;
	}

	public TextView getStart() {
		return start;
	}

	public TextView getEnd() {
		return end;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}

	public void setCheckColor(String checkColor) {
		this.checkColor = checkColor;
	}

	public RadioGroup getColorTab() {
		return colorTab;
	}

	public void setArrangeTypeInfo(ArrangeType arrangeTypeInfo) {
		this.arrangeTypeInfo = arrangeTypeInfo;
	}

	public static void go(Activity act, int arrangeTypeId, int curType) {

		Bundle args = new Bundle();
		args.putInt("arrange_type_id", arrangeTypeId);
		args.putInt("cur_type", curType);

		MyPageHelper.arrangeTypeEdit.showMyPage(act, args);
	}

	public static void go(Activity act) {

		MyPageHelper.arrangeTypeEdit.showMyPage(act);
	}

}
